% filename = 'interest_rate_one_month.csv';
% [num,txt,raw] = xlsread(filename);
% 
% ratio = 0.75;
% N = length(num);
% R = floor(N*ratio);

% clear all;
global Fval;

load data;
S = num(1:R); %in-sample
Model.Data = S;

% OPTION
if ~isfield(Model, 'MatlabDisp'), Model.MatlabDisp = 'off'; end;
options = optimset('LargeScale', 'off', 'MaxIter', 10000, 'MaxFunEvals', 10000, 'Display', Model.MatlabDisp, 'TolFun', 1e-8, 'TolX', 1e-7, 'TolCon', 1e-7); 
Model.pdf  = 'norm';
% Model.pdf = 'student';
% options = optimset('LargeScale', 'off', 'MaxIter', 10000, 'MaxFunEvals', 1000, 'Display', Model.MatlabDisp);
%if ~isfield(Model, 'Method'), Model.Method = 'besseli'; end;

%----------PARAMS----------% USER DEFINED
Name = 'S_CKLS';
%InitialParams = [-0.007697193621902;-3.319460287906360;0.001812506699763;6.069467767965504e-04;0.013620503882297;3.018164019776684e-05;8.500470316474065e-06;0.008478622023910;0.050086021813410;0.004459707072110]
ParamsInit = [0.000426338;-0.001844282;0.142603377;1.529289086]


%----------END PARAMS----------%

FvalPrev = Fval;
Model.Name = Name(3:end);
Exitflag = 0;  Count = 0; MaxCount = 5;
Param = ParamsInit;
fprintf('Estimate %d params from model %s',length(ParamsInit), Model.Name);
switch Name(1)
    case 'S'    %single factor
        while ~Exitflag && Count < MaxCount
            fprintf('.');
            [Param, Fval, Exitflag] =  fminsearch(@(Params) -sum(oneFactorModel (Params, Model)), Param, options);
            Count = Count + 1;
        end
        se = sterror2(Param,Model,@oneFactorModel)
    case 'G'    %GARCH        
        while ~Exitflag && Count < MaxCount
            fprintf('.');
            [Param, Fval, Exitflag] =  fminsearch(@(Params) -sum(garchModel(Params, Model)), Param, options);
            Count = Count + 1;
        end
        se = sterror(Param,Model,@garchModel)
    case 'R'    %regime switching
        while ~Exitflag && Count < MaxCount
            fprintf('.');
            [Param, Fval, Exitflag] =  fminsearch(@(Params) -sum(regimeSwitchingModel(Params, Model)), Param, options);
            Count = Count + 1;
        end
        if(Exitflag)
            se = sterror(Param,Model,@regimeSwitchingModel)
        end
    case 'J'    %jump diffusion
        while ~Exitflag && Count < MaxCount
            fprintf('.');
            FvalPrev = Fval;
            [Param, Fval, Exitflag,output] =  fminsearch(@(Params) -sum(jumpModel(Params, Model)), Param,options);
            if(Fval==-Inf)
                break;
            end
            Count = Count + 1;
        end
        if(Exitflag)
            se = sterror(Param,Model,@jumpModel)
        end
        
end

Param
